<template>
	<u-upload ref="upload"  :action="action" :max-size="5 * 1024 * 1024" max-count="1" :multiple="false" :before-upload="beforeUpload"
		:custom-btn="true" :show-progress="false" :deletable="false" :form-data="formData" :width="0" :height="0"
		@on-success="onSuccess">
		<u-avatar slot="addBtn" :src="vuex_user.avatar_url" size="140"></u-avatar>
	</u-upload>
</template>

<script>
	let _this = {}
	export default {
		name: "oss-upload",
		data() {
			return {
				action: '',
				formData: {},
				upFileName: ''
			};
		},
		created() {
			_this = this
		},
		methods: {
			async beforeUpload(index, list) {
				const {
					file
				} = list[0]
				//#ifdef H5
				const fileName = file.name
				//#endif 

				//#ifndef H5
				const fileName = file.path
				//#endif
				// console.log(fileName)
				const ossToken = await _this.$u.api.authOssToken()
				_this.action = ossToken.host
				const suffix = fileName.slice(fileName.lastIndexOf('.'))
				const upFileName = _this.$u.guid(20) + suffix
				_this.upFileName = upFileName
				_this.formData = {
					'key': upFileName,
					'policy': ossToken.policy,
					'OSSAccessKeyId': ossToken.accessid,
					'success_action_status': '200',
					'signature': ossToken.signature,
				}
				return true
			},
			//上传成功之后
			async onSuccess() {
				//移除预览区图片
				this.$refs.upload.remove(0)
				//请求api更新头像
				await this.$u.api.userAvatar({
					avatar: this.upFileName
				})
				//更新用户信息
				this.$u.utils.updataUser()
				this.$u.toast('更新成功')
			
			}
		},
	
	}
</script>

<style>

</style>
